package cn.com.lms.business.livecourse.web;

import cn.com.lms.business.core.util.CurrentUserInstance;
import cn.com.lms.business.livecourse.constant.TencentImConstants;
import cn.com.lms.business.livecourse.persistence.entity.CourseLive;
import cn.com.lms.business.livecourse.persistence.entity.TencentImAuth;
import cn.com.lms.business.livecourse.persistence.entity.rtc.AuthInfo;
import cn.com.lms.business.livecourse.persistence.entity.vod.AddLiveRecordVideoCompleteInfo;
import cn.com.lms.business.livecourse.persistence.entity.vod.BaseALiVodCallbackInfo;
import cn.com.lms.business.livecourse.service.AliRtcService;
import cn.com.lms.business.livecourse.service.AliVodService;
import cn.com.lms.business.livecourse.service.CourseLiveService;
import cn.com.lms.business.livecourse.service.TencentImService;
import cn.com.lms.business.user.persistence.entity.SysUserVo;
import com.aliyuncs.exceptions.ClientException;
import com.bnzj.core.exception.BusinessException;
import com.bnzj.core.rest.ResponseResult;
import com.bnzj.core.rest.ResultCode;
import com.google.gson.Gson;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;

@Tag(name = "课程直播", description = "课程直播API")
@RestController
@RequestMapping("/course/live")
public class LiveCourseController {

    @Autowired
    private AliVodService aliVodService;
    @Autowired
    private TencentImService tencentImService;
    @Autowired
    private CourseLiveService courseLiveService;


    @Operation(summary = "阿里云直播转点播录制完成回调通知", hidden = true)
    @PostMapping("/vod_callback")
    public String vodCallback(@RequestBody String callbackInfo) {
        System.out.println("接收到vod回调信息：" + callbackInfo);
        BaseALiVodCallbackInfo info = new Gson().fromJson(callbackInfo, BaseALiVodCallbackInfo.class);

        if (null != info && "success".equals(info.getStatus())) {
            // 直转点视频录制完成 事件
            if ("AddLiveRecordVideoComplete".equals(info.getEventType())) {
                // 更新直播课程信息
                AddLiveRecordVideoCompleteInfo alrdcInfo = new Gson().fromJson(callbackInfo, AddLiveRecordVideoCompleteInfo.class);
                courseLiveService.vodRecordComplete(alrdcInfo);

//                // 全部清晰度视频转码完成 事件
//            } else if ("TranscodeComplete".equals(info.getEventType())) {
//                // 更新课程信息
//                TranscodeCompleteInfo tcInfo = new Gson().fromJson(callbackInfo, TranscodeCompleteInfo.class);
//                if (null == tcInfo || 0 == tcInfo.getStreamInfos().size()) {
//                    return "fail";  // 回调信息异常
//                }
//                String vid = tcInfo.getVideoId();
//                String playUrl = tcInfo.getStreamInfos().get(0).getFileUrl();
//                Float duration = tcInfo.getStreamInfos().get(0).getDuration();
//                courseLiveService.saveLiveVodInfo(vid, playUrl, Integer.valueOf(Math.round(duration)));
            }
        }
        return "success";
    }

//    @PostMapping("/vod_callback")
//    public String vodCallback(@RequestBody String callbackInfo) {
////        String test = "{\n" +
////                "\"Status\":\"success\",\n" +
////                "\"VideoId\":\"818c1d009a4249c89836343259eae60c\",\n" +
////                "\"StreamName\":\"stream-7-1584413953\",\n" +
////                "\"RecordStartTime\":\"2020-03-17T03:00:11Z\",\n" +
////                "\"EventType\":\"AddLiveRecordVideoComplete\",\n" +
////                "\"DomainName\":\"bshb2.yurusee.com\",\n" +
////                "\"RecordEndTime\":\"2020-03-17T03:00:28Z\",\n" +
////                "\"UserId\":1144759210167505,\n" +
////                "\"EventTime\":\"2020-03-17T03:03:30Z\",\n" +
////                "\"AppName\":\"lms-live\"}";
////        AddLiveRecordVideoCompleteInfo info = new Gson().fromJson(body, AddLiveRecordVideoCompleteInfo.class);
////        System.out.println("info：" + info.toString());
//
//        System.out.println("接收到vod回调信息："+ callbackInfo);
//        BaseALiVodCallbackInfo info = new Gson().fromJson(callbackInfo, BaseALiVodCallbackInfo.class);
//
//        if (null != info && "success".equals(info.getStatus())) {
//            // 直转点视频录制完成 事件
//            if ("AddLiveRecordVideoComplete".equals(info.getEventType())) {
//                // 更新直播课程信息
//                AddLiveRecordVideoCompleteInfo alrdcInfo = new Gson().fromJson(callbackInfo, AddLiveRecordVideoCompleteInfo.class);
//                courseLiveService.vodRecordComplete(alrdcInfo);
//
//            }
//        }
//        return "success";
//    }

    /*@Operation(summary = "腾讯云即时聊天通讯IM回调通知", hidden = true)
    @PostMapping("/im_callback")
    public String imCallback() {
        System.out.println("接收到im回调信息：");



        String response = "\"{ActionStatus\": \"OK\",\"ErrorInfo\": \"\",\"ErrorCode\": 0\"}";
        return response;
    }*/

    @Operation(summary = "获取课程直播信息")
    @GetMapping("/{courseId}")
    public ResponseResult<CourseLive> courseLiveInfo(@Parameter(description = "课程主键", name = "courseId", required = true) @PathVariable(value = "courseId") long courseId) {
        if (0 >= courseId) {
            return ResponseResult.bizException(new BusinessException("参数异常", String.valueOf(ResultCode.FAILURE)));
        }
        CourseLive courseLive = null;
        try {
            courseLive = courseLiveService.courseLiveInfo(courseId);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.bizException(new BusinessException("结果异常", String.valueOf(ResultCode.FAILURE)));
        }
        return ResponseResult.success(courseLive);
    }

    @Operation(summary = "获取点播视频播放链接", hidden = true)
    @GetMapping("/vod/url/{vid}")
    public ResponseResult vodPlayUrl(@Parameter(description = "点播视频id", name = "vid",
            required = true) @PathVariable String vid) {
        String vodPlayUrl = "";
        try {
            vodPlayUrl = aliVodService.vodPlayUrl(vid);
        } catch (ClientException e) {
//            e.printStackTrace();
//            ResponseResult errorResp = ResponseResult.bizException(new BusinessException(e.getMessage() + "\n" + e.getErrMsg()));
//            errorResp.setData(vodPlayUrl);
            return ResponseResult.failure(0, e.getErrMsg());
//            return errorResp;
        }
        return ResponseResult.success(vodPlayUrl);
    }

    @Operation(summary = "修改课程直播状态",
            parameters = {
                    @Parameter(name = "courseId", description = "课程id", required = true, schema = @Schema(implementation = String.class)),
                    @Parameter(name = "status", description = "直播状态：1开始直播；2结束直播", required = true, schema = @Schema(implementation = String.class)),
            },
            responses = {
                    @ApiResponse(responseCode = "1", description = "更新成功", content = @Content(mediaType = "application/json", schema = @Schema(implementation = ResponseResult.class))),
                    @ApiResponse(responseCode = "0", description = "更新失败", content = @Content(mediaType = "application/json", schema = @Schema(implementation = ResponseResult.class)))})
    @GetMapping("/status/modify")
    public ResponseResult modifyLiveStatus(@RequestParam("courseId") long courseId, @RequestParam("status") int status) {
        if (0 >= courseId) {
            return ResponseResult.bizException(new BusinessException("课程参数异常", "0"));
        }
        if (1 != status && 2 != status) {
            return ResponseResult.bizException(new BusinessException("未支持的状态码", "0"));
        }

        try {
            // 查询课程直播信息
            CourseLive courseLive = courseLiveService.courseLiveInfo(courseId);
            if (null == courseLive || StringUtils.isEmpty(courseLive.getStreamName()) || StringUtils.isEmpty(courseLive.getPushUrl()) || StringUtils.isEmpty(courseLive.getChatRoomGroupId())) {
                return ResponseResult.bizException(new BusinessException("课程直播信息异常", String.valueOf(ResultCode.FAILURE)));
            }

            // 修改状态
            int result = courseLiveService.modifyLiveStatus(courseId, status);
            if (0 == result) {
                return ResponseResult.bizException(new BusinessException("修改课程直播状态失败", String.valueOf(ResultCode.FAILURE)));
            }

            HashMap<String, Object> taskResult = new HashMap<>();
            taskResult.put("success", true);
            if (1 == status) {
                if (0 == courseLive.getStatus()) {  // 直播状态为待直播时
                    // 开始rtc直播任务
                    taskResult = aliRtcService.startRtcLive(String.valueOf(courseId), courseLive.getStreamName(), courseLive.getPushUrl());
                }
            } else {
                if (1 == courseLive.getStatus()) {  // 直播状态为直播中时
                    // 停止rtc直播任务
                    taskResult = aliRtcService.stopRtcLive(courseLive.getStreamName());
                }
            }
            if (!((boolean) taskResult.get("success"))) {
                return ResponseResult.bizException(new BusinessException((String) taskResult.get("message"), String.valueOf(ResultCode.FAILURE)));
            }

            // 向课程聊天室推送直播开始指令
            String pushChatRoomMessage = "";
            if (1 == status) {
                pushChatRoomMessage = TencentImConstants.INSTRUCTION_START_LIVE;
            } else if (2 == status) {
                pushChatRoomMessage = TencentImConstants.INSTRUCTION_FINISH_LIVE;
            }
            if (!StringUtils.isEmpty(pushChatRoomMessage)) {
                boolean sendResult = tencentImService.sendGroupMessage(courseLive.getChatRoomGroupId(), pushChatRoomMessage);
                if (!sendResult) {
                    return ResponseResult.bizException(new BusinessException("聊天室推送直播开始指令失败", String.valueOf(ResultCode.FAILURE)));
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            String errorMessage = !StringUtils.isEmpty(e.getMessage()) ? e.getMessage() : "修改异常";
            return ResponseResult.bizException(new BusinessException(errorMessage, String.valueOf(ResultCode.FAILURE)));
        }
        return ResponseResult.success();
    }


    @GetMapping("/im/auth")
    @Operation(summary = "获取交互（即时通讯）授权信息", parameters = {
            @Parameter(name = "imUserId", description = "im应用使用的userId（lms使用姓名+工号作为imUserId）", required = true, schema = @Schema(implementation = String.class))
    })
    public ResponseResult<TencentImAuth> tencentImAuth() {
        SysUserVo user = CurrentUserInstance.getCurrentUser();
        if (null == user || StringUtils.isEmpty(user.getAccount())) {
            return ResponseResult.bizException(new BusinessException("用户信息异常", String.valueOf(ResultCode.FAILURE)));
        }
        TencentImAuth tia = tencentImService.genUserSign(user.getAccount());
        return ResponseResult.success(tia);
    }


    @Autowired
    AliRtcService aliRtcService;

    @Operation(summary = "获取PC端阿里云RTC授权登录信息", parameters = {
            @Parameter(name = "courseId", description = "课程id", required = true, schema = @Schema(implementation = Long.class)),
            @Parameter(name = "username", description = "用户名", required = true, schema = @Schema(implementation = String.class))
    })
    @GetMapping("/rtc/login")
    public ResponseResult<AuthInfo> rtcLogin(HttpServletRequest request, HttpServletResponse response) {
        SysUserVo user = CurrentUserInstance.getCurrentUser();
        if (null == user || StringUtils.isEmpty(user.getAccount())) {
            return ResponseResult.bizException(new BusinessException("用户信息异常", String.valueOf(ResultCode.FAILURE)));
        }
        AuthInfo authInfo = null;
        if (null != request.getParameter("courseId")) {
            long courseId = Long.parseLong(request.getParameter("courseId"));
            if (0 >= courseId) {
                return ResponseResult.bizException(new BusinessException("课程信息异常", String.valueOf(ResultCode.FAILURE)));
            }
            authInfo = aliRtcService.v1Login(String.valueOf(courseId), user.getAccount());
        }
        return ResponseResult.success(authInfo);
    }


    @Operation(summary = "上报直播观看者增加/减少", parameters = {
            @Parameter(name = "courseId", description = "课程id", required = true, schema = @Schema(implementation = Long.class)),
            @Parameter(name = "type", description = "上报类型：1增加；2减少", required = true, schema = @Schema(implementation = Integer.class))
    }, hidden = true)
    @GetMapping("/viewers/count")
    public ResponseResult<Long> reportViews(long courseId, int status) {
        if (courseId < 0 || (1 != status && 2 != status)) {
            return ResponseResult.bizException(new BusinessException("参数异常", String.valueOf(ResultCode.FAILURE)));
        }
        Long count = courseLiveService.incrOrDecrViewersCount(courseId, status);
        return ResponseResult.success(count);
    }


    @Operation(summary = "直播课程发起问卷", parameters = {
            @Parameter(name = "courseId", description = "课程id", required = true, schema = @Schema(implementation = Long.class))
    })
    @GetMapping("/initiateQuestionnaire")
    public ResponseResult initiateQuestionnaire(long courseId) {
        CourseLive courseLive;
        try {
            courseLive = courseLiveService.courseLiveInfo(courseId);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.bizException(new BusinessException(e.getMessage(), String.valueOf(ResultCode.FAILURE)));
        }
        if (null == courseLive || StringUtils.isEmpty(courseLive.getChatRoomGroupId())) {
            return ResponseResult.bizException(new BusinessException("直播课程信息异常", String.valueOf(ResultCode.FAILURE)));
        }
        boolean sendResult = tencentImService.sendGroupMessage(courseLive.getChatRoomGroupId(), TencentImConstants.INSTRUCTION_INITIATE_QUESTIONNAIRE);
        if (!sendResult) {
            return ResponseResult.bizException(new BusinessException("聊天室推送发起问卷指令失败", String.valueOf(ResultCode.FAILURE)));
        }
        return ResponseResult.success();
    }




   /* @GetMapping("/queryLiveStream")
    public Map<String, Object> queryLiveStream(String streamName) {
        HashMap<String, Object> result = aliRtcService.GetMPUTaskStatus(streamName);
        return result;
    }

    @PostMapping("/rtcStartLive")
    public Map<String, Object> rtcStartLive(long courseId, String streamName, String pushUrl) {
        // 开始rtc直播任务
        HashMap<String, Object> taskResult = aliRtcService.startRtcLive(String.valueOf(courseId),
                streamName, pushUrl);
        return taskResult;
    }*/
}
